package edu.upc.clase.stringcalculator;

/**
 * Hello world!
 *
 */
public class StringCalculator 
{
    String negatives = "";
    
    public StringCalculator() {}
    
    public int add(String s) {
        int res = eval(fixDelimiters(s));
        reportErrors(s);
        return res;
    }
    
    public void reportErrors(String s) {
        if (negatives.length() > 0) {
            throw new RuntimeException("negatives are not allowed :" + negatives);
        }        
    }
    
    public String fixDelimiters(String s) {
        String s1 = s;
        if (s.startsWith("//")) {
            s1 = s.replace(s.charAt(2),',').substring(2);
        }
        return s1;
    }
    
    public int eval(String s) {
        s = s.replaceAll("\n",",");
        int comma = s.indexOf(",");
        if (comma < 0) return toInt(s);
        
        return toInt(s.substring(0,comma)) + add(s.substring(comma+1));        
    }
    
    public int toInt(String s) {
        int n = s.isEmpty() ? 0 : Integer.parseInt(s);
        if (n < 0) negatives += " " + n;
        return n;
    }
    
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}
